package com.slashvision.im.eventbus

import androidx.lifecycle.*
import com.slashvision.im.ContextUtil
import com.slashvision.im.SLog
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * author : lizhenxin
 *  date  : 2021/9/28
 *  desc  :
 */
object Bus {
    private const val TAG = "BUS"
    private val busMap = mutableMapOf<String, EventBus<*>>()

    /**
     * Get EventBus
     * @return  returned object cannot be saved as a variable
     */
    @Synchronized
    fun <T> with(key: String): EventBus<T> {
        var eventBus = busMap[key]
        if (eventBus == null) {
            eventBus = EventBus<T>(key)
            busMap[key] = eventBus
        }
        return eventBus as EventBus<T>
    }

    class EventBus<T>(private val key: String) : LifecycleObserver {

        private val _events = MutableSharedFlow<T>() // private mutable shared flow
        val events = _events.asSharedFlow() // publicly exposed as read-only shared flow

        /**
         * need main thread execute
         */
        fun register(lifecycleOwner: LifecycleOwner, action: (t: T) -> Unit) {
            lifecycleOwner.lifecycle.addObserver(this)
            lifecycleOwner.lifecycleScope.launch {
                events.collect {
                    try {
                        action(it)
                    } catch (e: Exception) {
                        SLog.e(TAG, "KEY:%s---ERROR:%s".format(key, e.toString()))
                    }
                }
            }
        }

        /**
         * send value
         */
        fun post(event: T) {
            ContextUtil.getContext()
            GlobalScope.launch {
                _events.emit(event)
            }
        }

        /**
         * When subscriptionCount less than 0,remove event object in map
         */
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy() {
            val subscriptCount = _events.subscriptionCount.value
            if (subscriptCount <= 0)
                busMap.remove(key)
        }
    }
}